<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>问卷管理</el-breadcrumb-item>
      <el-breadcrumb-item>发布问卷</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <div class="header-form">
        <!-- 创建或者编辑标题 -->
        <h2 class="header-title">{{ title }}</h2>

        <div>
          <el-button
            type="primary"
            icon="el-icon-view"
            @click="previewDialogVisible = true"
            >预览问卷</el-button
          >
          <el-button type="primary" icon="el-icon-message" @click="savePaper"
            >保存问卷</el-button
          >
          <el-button type="primary" icon="el-icon-upload2" @click="publishPaper"
            >发布问卷</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-upload"
            @click="importTemplate"
            style="margin-left: 550px"
            >导入模板</el-button
          >
        </div>
      </div>

      <h3 class="quest-title">
        <el-input
          class="input_title"
          v-model="paperTitle"
          placeholder="请输入标题"
        ></el-input>
      </h3>

      <div class="quest-list">
        <QuestionEditor
          v-for="(quest, index) in questions"
          :key="quest.id"
          class="quest-box"
          v-model="questions[index]"
          @up="putUpQuest(index)"
          @down="putDownQuest(index)"
          @remove="removeQuest(index)"
        />

        <div class="quest-box quest-box-new" v-if="isShowAddBox">
          <el-button @click="addSingleQuest">单选题</el-button>
          <el-button @click="addMultipleQuest">多选题</el-button>
          <el-button @click="addTextQuest">文本题</el-button>
        </div>

        <el-button
          class="quest-box p-20"
          icon="el-icon-plus"
          @click="showQuestBox"
          >添加问题</el-button
        >
      </div>
    </el-card>

    <!-- 预览问卷 -->
    <el-dialog
      title="预览问卷"
      :visible.sync="previewDialogVisible"
      width="50%"
      @close="previewDialogClosed"
    >
      <el-card>
        <h3 class="quest-title" style="text-align: center">{{ paperTitle }}</h3>

        <div class="quest-list">
          <Question
            v-for="quest in questions"
            :key="quest.id"
            class="quest-box"
            :quest="quest"
          />

          <el-button
            type="primary"
            class="quest-box p-20"
            icon="el-icon-upload2"
            >提交</el-button
          >
        </div>
      </el-card>
    </el-dialog>

    <!-- 选择群组 -->
    <el-dialog
      title="选择群组"
      :visible.sync="groupDialogVisible"
      width="50%"
      @close="groupDialogClosed"
    >
      <!-- 卡片布局 -->
      <div v-if="dataShowType == 'gird'" class="project-grid-container">
        <div
          v-if="groupList.length"
          v-loading="groupListLoading"
          class="project-grid-view"
        >
          <div
            v-for="p in groupList"
            :key="p.gid"
            class="project-grid-item-view pointer"
          >
            <el-row align="middle" justify="center" type="flex">
              <el-col :span="19">
                <el-tooltip :content="p.groupName" placement="top">
                  <p class="project-title">
                    {{ p.groupName }}
                  </p>
                </el-tooltip>
              </el-col>
            </el-row>

            <!-- 相关操作 -->
            <div class="gird-operating-btns">
              <el-button type="text" @click="chooseG(p.gid)">
                <i class="el-icon-edit" />
                选择
              </el-button>
            </div>
          </div>
        </div>

        <!-- 数据为空时显示的界面 -->
        <div v-if="!groupListLoading && groupList.length == 0">
          <p>你没有群组，赶紧创建一个吧！！！</p>
        </div>
      </div>
      <!-- 分页组件 -->
      <div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfoG.pageNum"
          :page-sizes="[1, 4, 8, 16, 100]"
          :page-size="queryInfoG.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-dialog>

    <!-- 选择模板 -->
    <el-dialog
      title="选择模板"
      :visible.sync="templateDialogVisible"
      width="50%"
      @close="templateDialogClosed"
    >
      <!-- 卡片布局 -->
      <div v-if="dataShowType == 'gird'" class="project-grid-container">
        <div
          v-if="templateList.length"
          v-loading="templateListLoading"
          class="project-grid-view"
        >
          <div
            v-for="p in templateList"
            :key="p.qid"
            class="project-grid-item-view pointer"
          >
            <el-row align="middle" justify="center" type="flex">
              <el-col :span="19">
                <el-tooltip :content="p.title" placement="top">
                  <p class="project-title">
                    {{ p.title }}
                  </p>
                </el-tooltip>
              </el-col>
            </el-row>

            <!-- 相关操作 -->
            <div class="gird-operating-btns">
              <el-button type="text" @click="chooseT(p.qid)">
                <i class="el-icon-edit" />
                导入
              </el-button>
            </div>
          </div>
        </div>

        <!-- 数据为空时显示的界面 -->
        <div v-if="!templateListLoading && templateList.length == 0">
          <p>没有任何模板哟...</p>
        </div>
      </div>
      <!-- 分页组件 -->
      <div>
        <el-pagination
          @size-change="handleSizeChange1"
          @current-change="handleCurrentChange1"
          :current-page="queryInfoT.pageNum"
          :page-sizes="[1, 4, 8, 16, 100]"
          :page-size="queryInfoT.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total1"
        >
        </el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QuestionEditor from "@/components/questionnaire/paperEditor/components/QuestionEditor.vue";
import Question from "@/components/questionnaire/paperEditor/components/Question.vue"; //引入问卷模板
const TYPE_SINGLE_CHOICE = 1;
const TYPE_MULTIPLE_CHOICE = 2;
const TYPE_TEXT = 3;

export default {
  components: {
    QuestionEditor,
    Question,
  },
  data() {
    return {
      ...this.$route.query,
      title: "", //新建或者编辑标题
      paperTitle: "", //问卷标题
      questions: [], //题目
      listRemoveId: [], //
      isShowAddBox: false,
      previewDialogVisible: false, //预览问卷，起初为false
      groupDialogVisible: false, //选择群组，起初为false
      templateDialogVisible: false, //导入模板，起初为false
      isSaved: false, //该问卷是否已经保存，起初为false

      //问卷的请求query
      queryInfo: {
        query: "", //查询信息
        pageNum: 1, //当前页
        pageSize: 4, //每一页最大数
      },

      //群组的请求query
      queryInfoG: {
        query: "", //查询信息
        pageNum: 1, //当前页
        pageSize: 4, //每一页最大数
      },

      //模板的请求query
      queryInfoT: {
        query: "", //查询信息
        pageNum: 1, //当前页
        pageSize: 4, //每一页最大数
      },

      groupList: [], //记录group
      templateList: [], //记录template

      groupListLoading: false, //群组加载
      templateListLoading: false, //模板加载

      dataShowType: "gird", //卡片式布局

      total: 0, //群组的总记录数
      total1: 0, //模板的总记录数
    };
  },
  created() {
    this.getGroupList();
    this.getTemplateList();
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      switch (this.name) {
        case "新增问卷": {
          this.initAdd();
          break;
        }
        case "编辑问卷": {
          this.initEdit();
          break;
        }
      }
    },
    initAdd() {
      this.title = "新增问卷";
    },
    async initEdit() {
      this.title = "编辑问卷";

      const id = this.id + ""; //转变为字符串类型
      // console.log(typeof(id));
      await this.$http({
        method: "post",
        url: "/queryQuestionnairesByQidY",
        data: {
          query: id,
          pageNum: this.queryInfo.pageNum,
          pageSize: this.queryInfo.pageSize,
        },
      }).then((response) => {
        const paper = response.data.data.list[0]; //虽然传入list,默认取第一个
        this.paperTitle = paper.title;
        var questions = JSON.parse(paper.content);
        // console.log(questions);
        this.$nextTick(() => {
          questions.forEach((quest, index) => {
            const data = {
              id: quest.id,
              index: index,
              title: quest.title,
              type: quest.type,
              must: quest.must,
              setIndex: quest.setIndex,
            };

            if (quest.type !== TYPE_TEXT) {
              // const options = this.getOptionsByQuestionId(quest.id);
              var options = quest.options;
              data.options = options.map((option, index) => ({
                id: option.id,
                index: index,
                questionId: option.questionId,
                text: option.text,
              }));
            }

            if (quest.type === TYPE_TEXT) {
              data.tip = quest.tip;
            }
            this.isSaved = true;
            this.questions.push(data);
            // console.log(quest);
          });
        });
      });
    },

    putUpQuest(index) {
      const questions = this.questions;
      const quest = questions.splice(index, 1)[0];
      // console.log(quest)
      questions.splice(index - 1, 0, quest);
      // console.log(questions)
      this.resetIndex();
    },
    putDownQuest(index) {
      const questions = this.questions;
      const quest = questions.splice(index, 1)[0];
      questions.splice(index + 1, 0, quest);
      this.resetIndex();
    },
    removeQuest(index) {
      const quest = this.questions.splice(index, 1);
      quest.id && this.listRemoveId.push(quest.id);
      this.resetIndex();
    },
    resetIndex() {
      this.questions.forEach((quest, index) => {
        quest.index = index;
      });
    },

    toCharts(id) {
      this.$router.push({
        name: "charts",
        query: {
          id: id,
        },
      });
    },
    back() {
      this.$router.push({
        name: "home",
      });
    },
    // 保存问卷
    // 保存分为两种，一种是创建，一种是修改
    async savePaper() {
      let name = window.sessionStorage.getItem("name");
      const confirmResult = await this.$confirm("确认保存问卷?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);
      if (confirmResult != "confirm") {
        //取消
        return this.$message.info("已取消保存");
      }
      if (this.name === "新增问卷") {
        await this.$http({
          method: "post",
          url: "/createQuestionnaire",
          data: {
            name: name,
            title: this.paperTitle,
            content: JSON.stringify(this.questions),
          },
        }).then((res) => {
          if (res.data.code == "666") {
            // console.log(res);
            this.isSaved = true;
            this.$message.success(res.data.message);
            //由于创建新问卷时qid是后端生成的，所以跳到管理主界面，让用户再次点击
            this.$router.push("/sendq");
          } else {
            this.$message.error(res.data.message);
          }
        });
      } else if (this.name === "编辑问卷") {
        const id = this.id + "";
        await this.$http({
          method: "post",
          url: "/updateQuestionnaireContent",
          data: {
            qid:id,
            name:name,
            title: this.paperTitle,
            content: JSON.stringify(this.questions),
          },
        }).then((res) => {
          if (res.data.code == "666") {
            // console.log(res);
            this.isSaved = true;
            this.$message.success(res.data.message);
          } else {
            this.$message.error(res.data.message);
          }
        });
      } else {
        console.log("出现异常");
      }
    },
    async publishPaper() {
      if (this.isSaved) {
        //跳到群组选择
        this.groupDialogVisible = true;
      } else {
        this.$message.warning("您还没有保存该问卷，请先保存！");
      }
    },

    //获取群组
    async getGroupList() {
      let name = window.sessionStorage.getItem("name");
      await this.$http({
        method: "post",
        url: "/getGroupListY",
        data: {
          query: this.queryInfoG.query,
          pageNum: this.queryInfoG.pageNum,
          pageSize: this.queryInfoG.pageSize,
          name: name,
        },
      }).then((response) => {
        this.groupList = response.data.data.list;
        this.total = response.data.data.total;
        // console.log(this.groupList);
      });
    },

    //获取模板
    async getTemplateList() {
      await this.$http({
        method: "post",
        url: "queryTemplateByTitleY",
        data: {
          query: this.queryInfoT.query,
          pageNum: this.queryInfoT.pageNum,
          pageSize: this.queryInfoT.pageSize,
        },
      }).then((response) => {
        this.templateList = response.data.data.list;
        this.total1 = response.data.data.total;
      });
    },

    //关闭群组界面
    groupDialogClosed() {
      this.groupDialogVisible = false;
    },

    //选择群组
    async chooseG(gid) {
      let name = window.sessionStorage.getItem("name");
      const confirmResult = await this.$confirm(
        "确认发布问卷到此群组?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult != "confirm") {
        //取消
        return this.$message.info("已取消发布");
      }
      await this.$http({
        method: "post",
        url: "/issueQuestionnaireFirst",
        data: {
          qId: this.id,
          gId: gid,
          name: name,
        },
      }).then((res) => {
        if (res.data.code == "666") {
          // console.log(res);
          this.$message.success(res.data.message);
          this.$router.push("/sendq"); //发布成功返回问卷首页
        } else {
          this.$message.error(res.data.message);
        }
      });
    },

    //导入模板创建问卷
    importTemplate() {
      this.templateDialogVisible = true;
    },

    //确认导入模板
    async chooseT(qId) {
      const confirmResult = await this.$confirm("确认导入此模板?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);
      if (confirmResult != "confirm") {
        //取消
        return this.$message.info("已取消导入");
      }
      await this.$http({
        method: "post",
        url: "/queryQuestionnairesByQidY",
        data: {
          query: qId,
          pageNum: this.queryInfoT.pageNum,
          pageSize: this.queryInfoT.pageSize,
        },
      }).then((response) => {
        const paper = response.data.data.list[0]; //虽然传入list,默认取第一个
        this.paperTitle = paper.title;
        var questions = JSON.parse(paper.content);
        // console.log(questions);
        this.$nextTick(() => {
          questions.forEach((quest, index) => {
            const data = {
              id: quest.id,
              index: index,
              title: quest.title,
              type: quest.type,
              must: quest.must,
              setIndex: quest.setIndex,
            };

            if (quest.type !== TYPE_TEXT) {
              // const options = this.getOptionsByQuestionId(quest.id);
              var options = quest.options;
              data.options = options.map((option, index) => ({
                id: option.id,
                index: index,
                questionId: option.questionId,
                text: option.text,
              }));
            }

            if (quest.type === TYPE_TEXT) {
              data.tip = quest.tip;
            }

            this.questions.push(data);
            this.templateDialogVisible = false;
          });
        });
      });
    },

    //关闭导入模板界面
    templateDialogClosed() {
      this.templateDialogVisible = false;
    },

    //群组的分页函数
    handleSizeChange(newSize) {
      this.queryInfoG.pageSize = newSize;
      this.getGroupList();
    },
    handleCurrentChange(newPage) {
      this.queryInfoG.pageNum = newPage;
      this.getGroupList();
    },

    //模板的分页函数
    handleSizeChange1(newSize) {
      this.queryInfoT.pageSize = newSize;
      this.getTemplateList();
    },
    handleCurrentChange1(newPage) {
      this.queryInfoT.pageNum = newPage;
      this.getTemplateList();
    },

    showQuestBox() {
      this.isShowAddBox = true;
    },
    addQuest(type) {
      const data = {
        title: "",
        type: type,
        must: true,
        setIndex: -1, //不知道有啥用
      };

      switch (type) {
        case TYPE_SINGLE_CHOICE:
          //单选题
          data.options = [{ text: "" }, { text: "" }];
          break;
        case TYPE_MULTIPLE_CHOICE:
          //多选题
          data.options = [
            { text: "" },
            { text: "" },
            { text: "" },
            { text: "" },
          ];
          break;
        default:
          //文本题
          data.tip = "请输入答案";
      }

      this.questions.push(data);
      this.resetIndex();
    },
    addSingleQuest() {
      this.addQuest(TYPE_SINGLE_CHOICE);
      this.isShowAddBox = false;
    },
    addMultipleQuest() {
      this.addQuest(TYPE_MULTIPLE_CHOICE);
      this.isShowAddBox = false;
    },
    addTextQuest() {
      this.addQuest(TYPE_TEXT);
      this.isShowAddBox = false;
    },

    previewDialogClosed() {
      this.previewDialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.quest-list {
  padding: 20px;
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
}
.quest-box {
  width: 100%;
  margin-top: 20px;
  border-radius: 0;
}
.quest-box:first-child {
  margin-top: 0;
}
.quest-box-new {
  padding: 20px;
  border: 1px solid #dcdfe6;
  text-align: center;
}
/* 面包屑样式 */
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 17px;
}

.my-project-container {
  display: flex;
  width: 100%;
  height: 100%;
  flex-direction: column;
  align-items: center;
  align-content: center;
}

.back-view {
  display: flex;
  width: 80%;
  align-content: flex-start;
  margin: 10px;
}

.filter-view {
  margin-top: 20px;
  display: flex;
  flex-direction: row;
}

.show-view-type-icon {
  color: white;
  font-size: 18px;
  -webkit-text-stroke: 0.5px #a8a8a8;
  margin: 5px;
  cursor: pointer;
}

.show-view-type-icon-active {
  color: rgba(92, 155, 249, 100);
  -webkit-text-stroke: 0.5px rgba(92, 155, 249, 100);
}

.project-grid-container {
  margin-top: 20px;
  display: flex;
  width: 100%;
  justify-content: center;
}

.project-grid-view {
  display: flex;
  width: 1045px;
  flex-direction: row;
  flex-wrap: wrap;
}

.project-table-view {
  margin-top: 20px;
  width: 80%;
}

.project-grid-item-view {
  width: 169px;
  height: 199px;
  line-height: 20px;
  border-radius: 10px;
  background-color: rgba(255, 255, 255, 100);
  text-align: center;
  margin: 20px;
  position: relative;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);

  .project-title {
    color: rgba(16, 16, 16, 100);
    font-size: 14px;
    text-align: left;
    line-height: 20px;
    max-height: 20px;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .project-grid-view-status {
    display: inline-block;
    width: 7px;
    height: 7px;
    line-height: 20px;
    background-color: rgba(0, 110, 255, 100);
    text-align: center;
    border: 1px solid rgba(0, 110, 255, 100);
    border-radius: 20px;
  }
}

.gird-operating-btns {
  position: absolute;
  width: 100%;
  margin: 0;
  padding: 0;
  background-color: #f0f0f0;
  bottom: 0;
  display: none;
  border: none;
}

.project-grid-item-view:hover .gird-operating-btns {
  display: block;
}

.project-grid-view-preimg {
  width: 143px;
  height: 121px;
}

.project-grid-view-time {
  color: rgba(144, 147, 153, 100);
  font-size: 12px;
  line-height: 20px;
  text-align: center;
  margin: 0;
}

.project-page-view {
  margin-top: 30px;
}
</style>
